package wei.xinya.core.multiThread;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Completable {
    // 此executor线程池如果不传,CompletableFuture经测试默认只启用最多3个线程,所以最好自己指定线程数量
    static ExecutorService executor = Executors.newFixedThreadPool(15);

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        //参数
        List<String> params = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H");

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                params.stream().map(Completable::handle).toArray(CompletableFuture[]::new));

        allFutures.join();
        System.out.println("所有线程是否已执行完：" + allFutures.isDone());

        allFutures.whenComplete((aVoid, throwable) -> {
            System.out.println("执行后续操作");
            long end = System.currentTimeMillis();
            System.out.println("耗时:" + (end - start) / 1000L + "s");
        });
        System.out.println("流程结束");
    }

    // executor可不传入,则默认最多3个线程
    static CompletableFuture<Void> handle(String link) {
        //捕捉异常,不会导致整个流程中断
        return CompletableFuture.runAsync(() -> {
            System.out.println("执行任务：" + link);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor).exceptionally(throwable -> {
            System.out.println("线程[{" + Thread.currentThread().getName() + "}]发生了异常");
            return null;
        });
    }
}